import nodemailer from "nodemailer"
import { logger } from "../utils"

import type { ImailOptions } from "./types"
import { SUCCESS_RESULT } from "../utils"
import fs from "fs"
import ejs from "ejs"

class MAILCONTENT {
  sendmail(obj: ImailOptions) {
    return new Promise((resolve, reject) => {
      const {
        mailFrom,
        mailTo,
        mailCc,
        mailBcc,
        mailSubject,
        mailHtml,
        mailData,
      } = obj

      const transporter = nodemailer.createTransport({
        host: "mail.compeq.huizhou.gd.cn",
        port: 25,
        secure: false,
        tls: {
          rejectUnauthorized: false,
        },
      })

      let mailContent = mailHtml

      //如果是template,则读取模板,否则直接发送内容
      if (mailContent.indexOf(".ejs") !== -1) {
        try {
          const template = fs.readFileSync(mailContent, "utf8")
          mailContent = ejs.render(template, mailData)
        } catch (error) {
          logger.error("读取文件异常!" + error)
          return reject(error)
        }
      }
      const mailOptions = {
        from: mailFrom,
        to: mailTo,
        cc: mailCc,
        bcc: mailBcc,
        subject: mailSubject,
        html: mailContent,
      }

      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          logger.error(error)
          reject(error)
        } else {
          logger.trace(info.messageId, info.response,`to:${mailTo}`,`cc:${mailCc}`,`subject:${mailSubject}`)
          resolve(SUCCESS_RESULT)
        }
      })
    })
  }
}

export default new MAILCONTENT()
